package com.tzy.for10evalue.utils.localcache;

import com.google.common.base.Optional;
import com.google.common.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;

/**
 * @author tzy
 * @date 2022/3/21 15:47
 */
public class LocalCacheTemplate {

    private static Logger log = LoggerFactory.getLogger(LocalCacheTemplate.class);

    public static <V> V get(Cache<String, Optional<V>> cache, String cacheKey, Callable<? extends V> valueLoader) {
        try {
            Optional<V> result = cache.get(cacheKey, () -> Optional.fromNullable(null));
            //本地缓存是否有数据
            if (!result.isPresent()) {
                //获取同步锁
                String cacheName = cacheKey.substring(0, cacheKey.indexOf("-"));
                Object lock = LockUtil.getLock(cacheName, cacheKey);
                synchronized (lock) {
                    result = cache.get(cacheKey, () -> Optional.fromNullable(null));
                    if (!result.isPresent()) {
                        if(!cacheKey.startsWith(BusinessCache.zoneLabelPre)) {
                            log.info("获取数据-key=" + cacheKey);
                        }
                        //缓存中没有数据，从数据库或其它数据来源中获取
                        V value = valueLoader.call();
                        //加入本地缓存
                        result = Optional.fromNullable(value);
                        cache.put(cacheKey, result);
                    }
                }
            }
            return result.get();
        }catch (Exception e){
            return null;
        }

    }
}
